package com.ruoyi.module.szLiveRoom.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamOnlineListRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamOnlineListResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @author yqq
 * @date 2023/10/18
 * @Description 直播工具类
 */
@Slf4j
public final class ZBUtil {
    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /*
     * 生成txSecret
     */
    public static String getSafeUrl(String key, String streamName, long txTime) {
        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();

        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret  = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            log.error("直播获取url失败1:",e);
        } catch (UnsupportedEncodingException e) {
            log.error("直播获取url失败2:",e);
        }

        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }
    /**
     * 查询在线直播流
     */
    public static String getStarting(){
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential("AKID9GTfoqlw6DZckvcKtKhRFBDKSeqgZ3b9", "SecretKey");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("live.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            LiveClient client = new LiveClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeLiveStreamOnlineListRequest req = new DescribeLiveStreamOnlineListRequest();
            req.setPageNum(0L);
            req.setPageSize(1L);
            // 返回的resp是一个DescribeLiveStreamOnlineListResponse的实例，与请求对象对应
            DescribeLiveStreamOnlineListResponse resp = client.DescribeLiveStreamOnlineList(req);
            // 输出json格式的字符串回包
            System.out.println(DescribeLiveStreamOnlineListResponse.toJsonString(resp));
            return DescribeLiveStreamOnlineListResponse.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            log.error("获取在线直播间失败：",e);
            return "";
        }
    }

    /**
     * 获取UUIX时间戳
     * @return
     */
    public static Long getTime(){
        //获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        //日期时间加上24小时
        LocalDateTime after24hours = now.plusHours(24);
        return after24hours.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
    }


}
